using System;
using System.Web.UI.WebControls;
using EPiServer.Web.PropertyControls;

namespace EPiBoost.Core.CustomProperties.EnumSelector
{
	/// <summary>
	/// PropertyControl implementation used for rendering PropertyEnumSelectorBase data.
	/// </summary>
	public class SingleEnumSelectorControl<T> : PropertyDropDownListControl where T : struct
	{   
		System.Web.UI.WebControls.DropDownList _DropDown = new System.Web.UI.WebControls.DropDownList();
		
		/// <summary>
		/// Gets the PropertyEnumSelectorBase instance for this IPropertyControl.
		/// </summary>
		/// <value>The property that is to be displayed or edited.</value>
		public PropertyEnumSelectorBase<T> PropertyEnumSelectorBase
		{
			get
			{
				return PropertyData as PropertyEnumSelectorBase<T>;
			}
		}

		public override void CreateEditControls() 
		{
			var options = EnumHelper.GetEnumCollectionFromEnum<T>(true);
			
			foreach (var option in options)
			{
				AddListItem(option);
			}

			SetSelectedValue();

			this.ApplyControlAttributes(_DropDown);
			this.EditControl = _DropDown;
			Controls.Add(this.EditControl);
		}

		public override void ApplyEditChanges()
		{
			if(_DropDown!=null)
			{
				this.PropertyData.Value = _DropDown.SelectedValue;
			}
		}
		
		private void AddListItem(SelectedEnum<T> option)
		{
			var li = new ListItem(option.Value.ToString(), option.Value.ToString());
			if (option.Attributes != null && !string.IsNullOrWhiteSpace(option.Attributes.DisplayName))
			{
				li.Text = option.Attributes.DisplayName;
			}
			if(option.Attributes!=null && option.Attributes.Hidden)
			{
				li.Enabled = false; // hidden item
				li.Text += " (Hidden)";
			}
			_DropDown.Items.Add(li);
		}

		private void SetSelectedValue()
		{
			if (this.PropertyData != null && this.PropertyData.Value != null)
			{
				string val = PropertyData.Value.ToString();
				var selected = _DropDown.Items.FindByValue(val);
				if (selected != null)
				{
					_DropDown.SelectedValue = val;
					selected.Enabled = true; // show hidden
				}
			}
		}
	}
}
